package system.service.sys.impl;

import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import system.entity.SysRoleUser;
import system.mapper.SysRoleMapper;
import system.mapper.SysRoleUserMapper;
import system.service.sys.SysConfigService;
import system.service.sys.SysRoleUserService;
import system.service.sys.SysUserService;

import java.util.List;

@Service
public class SysRoleUserServiceImpl implements SysRoleUserService {
    @Autowired
    @Getter
    private SysRoleUserMapper mapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Lazy
    @Autowired
    private SysUserService sysUserService;
    @Lazy
    @Autowired
    private SysConfigService sysConfigService;

    @Override
    public Integer add(SysRoleUser param) {
        Integer rows = SysRoleUserService.super.add(param);
        sysConfigService.updateConfigVersion();
        return rows;
    }

    @Override
    public Integer deleteById(Integer id) {
        Integer rows = SysRoleUserService.super.deleteById(id);
        sysConfigService.updateConfigVersion();
        return rows;
    }

    @Override
    @Transactional
    public int setUserRoles(Long userId, List<Integer> roleIds) {
        int rows = 0;
        //
        SysRoleUser ru = new SysRoleUser();
        ru.setUserId(userId);
        rows += mapper.delete(ru);
        //
        for (Integer roleId : roleIds) {
            ru = new SysRoleUser();
            ru.setRoleId(roleId);
            ru.setUserId(userId);
            rows += mapper.add(ru);
            //更新用户数
            rows += roleMapper.refreshMemberCount(roleId);
        }
        //
        sysUserService.cacheUserDelete(userId);
        sysConfigService.updateConfigVersion();
        //
        return rows;
    }
}